package com.xinchuang.utils;

import com.xinchuang.entity.Edtion;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/10/31 10:07
 */
public class EntityComparator {

  /*  public static void main(String[] args) {
        Edtion user1 = new Edtion();
        Edtion user2 = new Edtion();

        user1.setId("123");
        user2.setId("465");

        List<String> differentFields = EntityComparator.compareFields(user1, user2);
        if (differentFields.isEmpty()) {
            System.out.println("两个实体类的字段值完全一致");
        } else {
            System.out.println("字段值不一致的字段列表：" + differentFields);
        }
    }*/

    public static <T> List<String> compareFields(T entity1, T entity2) {
        List<String> differentFields = new ArrayList<>();

        PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(entity1.getClass());
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            Object value1 = getProperty(propertyDescriptor, entity1);
            Object value2 = getProperty(propertyDescriptor, entity2);

            if (value1 != null && !value1.equals(value2)) {
                differentFields.add(propertyName);
            } else if (value2 != null && !value2.equals(value1)) {
                differentFields.add(propertyName);
            }
        }

        return differentFields;
    }

    private static Object getProperty(PropertyDescriptor propertyDescriptor, Object entity) {
        try {
            return propertyDescriptor.getReadMethod().invoke(entity);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
